package com.liveinstars.common.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * emoji转码和还原
 * Created by guoyanjiang on 2018/6/28.
 */
public class EmojiUtil {

    public static String emojiFilter(String str) throws UnsupportedEncodingException {
        String patternString = "([\\x{10000}-\\x{10ffff}\ud800-\udfff])";

        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(str);

        StringBuffer sb = new StringBuffer();
        while(matcher.find()) {
            matcher.appendReplacement(sb, "[[EMOJI:" + URLEncoder.encode(matcher.group(1),"UTF-8") + "]]");
        }
        matcher.appendTail(sb);

        return sb.toString();
    }

    public static String emojiRecovery(String str) throws UnsupportedEncodingException {
        String patternString = "\\[\\[EMOJI:(.*?)\\]\\]";

        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(str);

        StringBuffer sb = new StringBuffer();
        while(matcher.find()) {
            matcher.appendReplacement(sb, URLDecoder.decode(matcher.group(1),"UTF-8"));
        }
        matcher.appendTail(sb);

        return sb.toString();
    }
}
